<template>
  <div class="dashboard-container">
    <h1>欢迎使用小微资产管理系统</h1>
    <div class="dashboard-cards">
      <el-card class="info-card">
        <div class="card-content">
          <div class="card-title">总资产数量</div>
          <div class="card-value">{{ overviewData.totalCount || 0 }}</div>
        </div>
      </el-card>
      <el-card class="info-card">
        <div class="card-content">
          <div class="card-title">总资产价值</div>
          <div class="card-value">¥{{ formatMoney(overviewData.totalValue || 0) }}</div>
        </div>
      </el-card>
      <el-card class="info-card">
        <div class="card-content">
          <div class="card-title">近30天新增</div>
          <div class="card-value">{{ overviewData.newAssetsCount || 0 }}</div>
        </div>
      </el-card>
      <el-card class="info-card">
        <div class="card-content">
          <div class="card-title">近30天报废</div>
          <div class="card-value">{{ overviewData.scrapAssetsCount || 0 }}</div>
        </div>
      </el-card>
    </div>
    
    <div class="charts-container">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产状态分布</span>
          </div>
        </template>
        <div id="statusChart" class="chart"></div>
      </el-card>
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产分类分布</span>
          </div>
        </template>
        <div id="categoryChart" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getAssetOverviewAPI,getAssetStatusDistributionAPI,getAssetCategoryDistributionAPI } from '@/api/asset.js'
import { ElMessage } from 'element-plus'

// 仪表盘概览数据（总数量、总价值等）
const overviewData = ref({
  totalCount: 0,
  totalValue: 0,
  newAssetsCount: 0,
  scrapAssetsCount: 0
})
// 图表实例
const statusChart = ref(null)
const categoryChart = ref(null)
//图表数据
let assetList = []
let assetList1 = []

const loadDashboardData = async () => {
  try {
    const res = await getAssetOverviewAPI()
    const res1 = await getAssetStatusDistributionAPI()
    const res2 = await getAssetCategoryDistributionAPI()

    if (res.data.code === 200 && res1.data.code == 200 && res2.data.code == 200 ) {
      overviewData.value = res.data.data
      assetList = res1.data.data
      assetList1 = res2.data.data
      initStatusChart(assetList)//传入全量数据统计状态分布
      initCategoryChart(assetList1)//传入全量数据统计分类分
    } else {
      // 无数据时重置
      overviewData.value = {
        totalCount: 0,
        totalValue: 0,
        newAssetsCount: 0,
        scrapAssetsCount: 0
      }
      resetCharts()
      ElMessage.warning('暂无资产数据')
    }
  } catch (error) {
    console.error('加载仪表盘数据失败：', error)
    overviewData.value = {
      totalCount: 0,
      totalValue: 0,
      newAssetsCount: 0,
      scrapAssetsCount: 0
    }
    resetCharts()
    ElMessage.error('数据加载失败，请重试')
  }
}

// 初始化资产状态饼图（基于全量资产数据统计）
const initStatusChart = (assetList) => {
  const chartDom = document.getElementById('statusChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (statusChart.value) {
    statusChart.value.dispose()
  }

  statusChart.value = echarts.init(chartDom)

  const pieData = assetList.map(item => ({
    name: item.status,
    value: item.count
  }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}台 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: assetList.map(item => item.status)
    },
    series: [
      {
        name: '资产状态',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter:'{b}: {c} ({d}%)'
        }
      }
    ],
    // 无数据提示
    graphic: assetList.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  statusChart.value.setOption(option)
}

// 初始化资产分类饼图（基于全量资产数据统计）
const initCategoryChart = (assetList1) => {
  const chartDom = document.getElementById('categoryChart')
  if (!chartDom) return

  // 销毁旧实例
  if (categoryChart.value) {
    categoryChart.value.dispose()
  }

  categoryChart.value = echarts.init(chartDom)

  const pieData = assetList1.map(item => ({
    name: item.categoryName,
    value: item.count
  }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}台 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: assetList1.map(item => item.categoryName)
    },
    series: [
      {
        name: '资产分类',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter:'{b}: {c} ({d}%)'
        }
      }
    ],
    // 无数据提示
    graphic: assetList1.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  categoryChart.value.setOption(option)
}


// 重置图表为无数据状态
const resetCharts = () => {
  initStatusChart([])
  initCategoryChart([])
}

// 图表自适应窗口大小
const handleResize = () => {
  statusChart.value && statusChart.value.resize()
  categoryChart.value && categoryChart.value.resize()
}

// 金额格式化（用于模板显示）
const formatMoney = (value) => {
  return value.toLocaleString('zh-CN')
}

// 组件挂载时加载数据并初始化图表
onMounted(() => {
  loadDashboardData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表+移除事件
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  statusChart.value && statusChart.value.dispose()
  categoryChart.value && categoryChart.value.dispose()
})

// 暴露金额格式化方法给模板
defineExpose({
  formatMoney
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-container h1 {
  margin-bottom: 20px;
  color: #333;
}

.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  transition: transform 0.3s ease;
}

.info-card:hover {
  transform: translateY(-5px);
}

.card-content {
  text-align: center;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 320px;
}
</style>